package com.ccom.starter.file.serviceImpl;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.ccom.core.common.exception.CcomBootException;
import com.ccom.starter.file.service.OOSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * amazon客户端实现
 */
public class OOSServiceAmazonImpl implements OOSService {

    private static Logger logger = LoggerFactory.getLogger(OOSServiceAmazonImpl.class);
    /**
     * 默认桶
     */
    private String bucketName;
    /**
     * AmazonS3客户端
     */
    private AmazonS3 amazonS3;
    /**
     * 用于对接数据中心amazon s3的copyObject、putObject接口，key、value由数据中心提供，可缺省
     */
    private Map<String, String> dateKeyValueMap;

    public OOSServiceAmazonImpl(String bucketName, AmazonS3 amazonS3, Map<String, String> dateKeyValueMap) {
        this.bucketName = bucketName;
        this.amazonS3 = amazonS3;
        this.dateKeyValueMap = dateKeyValueMap;
    }

    private String bucketName() {
        return this.bucketName;
    }

    @Override
    public void uploadFile(String oosKey, InputStream in) {
        try {
            if (!amazonS3.doesBucketExist(bucketName())) {
                amazonS3.createBucket(bucketName());
            }
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(in.available());
            if (null != dateKeyValueMap) {
                objectMetadata.setUserMetadata(dateKeyValueMap);
            }
            amazonS3.putObject(bucketName(), oosKey, in, objectMetadata);
        } catch (Exception e) {
            logger.error("AmazonS3 上传文件出错,bucket:{},oosKey:{}", bucketName(), oosKey);
            throw new CcomBootException(e.getMessage());
        }

    }

    @Override
    public void uploadFile(String oosKey, String content) {
        try (InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) {
            uploadFile(oosKey, inputStream);
        } catch (IOException e) {
            logger.error("AmazonS3 上传文件出错", e);
        }
    }

    @Override
    public InputStream downloadFile(String oosKey) {
        try {
            S3Object s3 = amazonS3.getObject(bucketName(), oosKey);
            return s3.getObjectContent();
        } catch (Exception e) {
            logger.warn("AmazonS3 下载文件出错或文件不存在,bucket:{},oosKey:{}", bucketName(), oosKey);
        }
        return null;
    }

    @Override
    public void deleteFile(String oosKey) {
        try {
            amazonS3.deleteObject(bucketName(), oosKey);
        } catch (Exception e) {
            logger.warn("AmazonS3 删除文件出错或文件不存在,bucket:{},oosKey:{}", bucketName(), oosKey);
        }
    }

    @Override
    public boolean existsFile(String oosKey) {
        try {
            amazonS3.getObjectMetadata(bucketName(), oosKey);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void copy(String from, String target) {
        try {
            CopyObjectRequest request = new CopyObjectRequest(bucketName(), from, bucketName(), target);
            if (null != dateKeyValueMap) {
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setUserMetadata(dateKeyValueMap);
                request.setNewObjectMetadata(objectMetadata);
            }
            amazonS3.copyObject(request);
        } catch (Exception e) {
            logger.error("AmazonS3 拷贝文件出错或文件不存在,bucket:" + bucketName() + ",from:" + from + ",target:" + target, e);
            throw new CcomBootException(e.getMessage());
        }
    }

    @Override
    public void uploadflowBatchResult(File file) {
        String oosKey = "flowBatchResult/" + file.getName();
        try (InputStream is = new FileInputStream(file)) {
            uploadFile(oosKey, is);
        } catch (Exception e) {
            logger.error("uploadflowBatchResult", e);
            throw new CcomBootException(e.getMessage());
        }
    }

    @Override
    public InputStream downloadFileByBucket(String oosKey, String bucketName) {
        try {
            S3Object s3 = amazonS3.getObject(bucketName, oosKey);
            return s3.getObjectContent();
        } catch (Exception e) {
            logger.warn("AmazonS3 下载文件出错或文件不存在,bucket:{},oosKey:{}", bucketName, oosKey);
        }
        return null;
    }

    @Override
    public void uploadFileByBucket(String bucketName, String oosKey, InputStream in) {
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(in.available());
            if (null != dateKeyValueMap) {
                objectMetadata.setUserMetadata(dateKeyValueMap);
            }
            amazonS3.putObject(bucketName, oosKey, in, objectMetadata);
        } catch (Exception e) {
            logger.error("AmazonS3 上传文件出错,bucket:{},oosKey:{}", bucketName, oosKey);
            throw new CcomBootException(e.getMessage());
        }
    }
}
